package com.lekang.system.service.impl;

import java.util.Date;
import java.util.List;
import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.system.domain.LeaveRequest;
import com.lekang.system.domain.PendingTasks;
import org.springframework.transaction.annotation.Transactional;
import com.lekang.system.service.ILeaveRequestService;
import com.lekang.system.service.IPendingTasksService;
import com.lekang.system.service.ICheckOutManagementService;
import org.activiti.engine.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lekang.system.mapper.AccraditationRecordMapper;
import com.lekang.system.domain.AccraditationRecord;
import com.lekang.system.service.IAccraditationRecordService;

/**
 * 审批记录Service业务层处理
 * 
 * @author zihao
 * @date 2025-10-18
 */
@Service
public class AccraditationRecordServiceImpl implements IAccraditationRecordService 
{
    @Autowired
    private AccraditationRecordMapper accraditationRecordMapper;

    /**
     * 查询审批记录
     * 
     * @param id 审批记录主键
     * @return 审批记录
     */
    @Override
    public AccraditationRecord selectAccraditationRecordById(Long id)
    {
        return accraditationRecordMapper.selectAccraditationRecordById(id);
    }

    /**
     * 查询审批记录列表
     * 
     * @param accraditationRecord 审批记录
     * @return 审批记录
     */
    @Override
    public List<AccraditationRecord> selectAccraditationRecordList(AccraditationRecord accraditationRecord)
    {
        return accraditationRecordMapper.selectAccraditationRecordList(accraditationRecord);
    }

    /**
     * 新增审批记录
     * 
     * @param accraditationRecord 审批记录
     * @return 结果
     */
    @Autowired
    private TaskService taskService;
    @Autowired
    private IPendingTasksService pendingTasksService;
    @Autowired
    private ILeaveRequestService requestService;
    @Autowired
    private ICheckOutManagementService checkOutManagementService;
    @Override
    @Transactional
    public int insertAccraditationRecord(AccraditationRecord accraditationRecord)
    {
        //审批 --拒绝 同意
        // 1.处理数据
        accraditationRecord.setCreateTime(DateUtils.getNowDate());
        Long ptId = accraditationRecord.getHandleType();
        String taskId = accraditationRecord.getExtraField1();
        Long busId = accraditationRecord.getBussniessId();
        
        // 1.5 权限检查：根据业务类型进行不同的权限检查
        Long currentUserId = SecurityUtils.getUserId();
        System.out.println("=== 审批权限检查 ===");
        System.out.println("当前审批人ID: " + currentUserId);
        System.out.println("业务ID: " + busId);
        System.out.println("业务类型: " + accraditationRecord.getType());
        
        // 根据业务类型进行权限检查
        if (busId != null) {
            Long businessType = accraditationRecord.getType();
            
            if (businessType != null && businessType == 1L) {
                // 退住申请权限检查
                System.out.println("=== 退住申请权限检查 ===");
                com.lekang.system.domain.CheckOutManagement checkOut = checkOutManagementService.selectCheckOutManagementById(busId);
                if (checkOut != null && checkOut.getCreator() != null) {
                    System.out.println("退住申请创建人ID: " + checkOut.getCreator());
                    
                    // 如果当前用户就是退住申请的创建人，禁止审批
                    if (currentUserId.equals(checkOut.getCreator())) {
                        System.out.println("权限检查失败：护理员不能审批自己的退住申请");
                        throw new RuntimeException("你没有此权限功能");
                    }
                    System.out.println("退住申请权限检查通过");
                }
            } else if (businessType != null && businessType == 2L) {
                // 请假申请权限检查
                System.out.println("=== 请假申请权限检查 ===");
                LeaveRequest leaveRequest = requestService.selectLeaveRequestById(busId);
                if (leaveRequest != null && leaveRequest.getCreator() != null) {
                    System.out.println("请假申请创建人ID: " + leaveRequest.getCreator());
                    
                    // 如果当前用户就是请假申请的创建人，禁止审批
                    if (currentUserId.equals(leaveRequest.getCreator())) {
                        System.out.println("权限检查失败：护理员不能审批自己的请假申请");
                        throw new RuntimeException("你没有此权限功能");
                    }
                    System.out.println("请假申请权限检查通过");
                }
            } else {
                System.out.println("未知业务类型，跳过权限检查");
            }
        }
        
        // 2.向数据库添加一条审批记录（同意/拒绝）
        // 注意：不要硬编码type，应该从前端传递或根据业务判断
        // accraditationRecord.setType(2L); // 不要硬编码
        if (accraditationRecord.getType() == null) {
            accraditationRecord.setType(1L); // 默认退住申请
        }
        accraditationRecord.setFinishTime(new Date());
        accraditationRecord.setApproverId(SecurityUtils.getUserId());
        accraditationRecord.setApproverName(SecurityUtils.getUsername());
        accraditationRecord.setApproverNameRole("护理组长");  // 需要你们自己查询
        accraditationRecord.setCurrentStep("审批-申请审批");
        // 保持前端传递的审批状态，不强制设置为通过
        // accraditationRecord.setAuditStatus(1L); // 删除这行，使用前端传递的状态
        accraditationRecord.setStepNo(2L);  // 步骤2
        accraditationRecord.setHandleType(1L);
        int i = accraditationRecordMapper.insertAccraditationRecord(accraditationRecord);
        
        System.out.println("=== 审批记录已创建 ===");
        System.out.println("业务类型: " + accraditationRecord.getType());
        System.out.println("步骤号: " + accraditationRecord.getStepNo());
        
        // 3.根据taskId来结束节点（首提可能没有taskId，此时跳过complete）
        if (taskId != null && !taskId.trim().isEmpty()) {
            taskService.complete(taskId);
            System.out.println("✅ 完成工作流任务（步骤2）: " + taskId);
        }
        
        // 4. ✅ 更新当前待办任务状态为已处理（is_handle = 1），而不是删除
        if (ptId != null) {
            com.lekang.system.domain.PendingTasks currentTask = pendingTasksService.selectPendingTasksById(ptId);
            if (currentTask != null) {
                currentTask.setIsHandle(1L); // ✅ 设置为已处理
                currentTask.setFinishTime(new Date());
                pendingTasksService.updatePendingTasks(currentTask);
                System.out.println("✅ 更新步骤2待办任务状态为已处理: " + ptId);
            }
        }
        // 5.修改我的申请中的步骤 3
        // 6.根据业务类型修改对应的业务数据状态
        Long businessType = accraditationRecord.getType();
        if (businessType != null) {
            if (businessType == 1L) {
                // 退住申请
                System.out.println("=== 处理退住申请审批 ===");
                System.out.println("业务ID: " + busId);
                System.out.println("审批状态: " + accraditationRecord.getAuditStatus());
                System.out.println("当前步骤: " + accraditationRecord.getStepNo());
                
                // 查询退住申请记录
                com.lekang.system.domain.CheckOutManagement checkOut = checkOutManagementService.selectCheckOutManagementById(busId);
                if (checkOut != null) {
                    System.out.println("=== 开始处理退住申请审批记录 ===");
                    System.out.println("业务ID: " + busId);
                    System.out.println("审批状态: " + accraditationRecord.getAuditStatus() + " (1=通过, 2=拒绝)");
                    System.out.println("审批步骤: " + accraditationRecord.getStepNo());
                    System.out.println("审批意见: " + accraditationRecord.getOpinion());
                    System.out.println("待办任务ID: " + accraditationRecord.getHandleType());
                    System.out.println("工作流任务ID: " + accraditationRecord.getExtraField1());
                    
                    // 根据审批结果更新退住申请状态
                    if (accraditationRecord.getAuditStatus() == 1) {
                        // 审批通过，继续下一步流程
                        System.out.println(">>> 处理审批通过逻辑 <<<");
                        System.out.println("退住申请审批通过，流程继续");
                        
                        // 查询下一个任务节点
                        org.activiti.engine.task.Task nextTask = taskService.createTaskQuery()
                            .processInstanceBusinessKey(busId.toString())
                            .processDefinitionKey("tuizhu")
                            .singleResult();
                        
                        if (nextTask != null) {
                            System.out.println("查询到下一个任务: " + nextTask.getName());
                            System.out.println("下一个任务分配人: " + nextTask.getAssignee());
                            
                            // 根据当前步骤和下一个任务名称，确定下一步操作
                            String nextStepName = getNextStepName(nextTask.getName(), accraditationRecord.getStepNo());
                            String nextApproverRole = getNextApproverRole(nextTask.getName());
                            
                            // 创建下一个待办任务（步骤3）
                            com.lekang.system.domain.PendingTasks nextPendingTask = new com.lekang.system.domain.PendingTasks();
                            nextPendingTask.setBussniessId(busId);
                            nextPendingTask.setTaskId(nextTask.getId()); // ✅ 新的taskId
                            nextPendingTask.setTitle(checkOut.getElderly().getName() + "退住申请");
                            nextPendingTask.setType(1L); // ✅ 修正：退住申请=1，不是2
                            nextPendingTask.setAssignee(nextTask.getAssignee());
                            nextPendingTask.setAssigneeId(Long.valueOf(nextTask.getAssignee()));
                            nextPendingTask.setStatus(1L);
                            nextPendingTask.setApplicationTime(new Date());
                            nextPendingTask.setApplicat(SecurityUtils.getUsername());
                            nextPendingTask.setApplicatId(SecurityUtils.getUserId());
                            nextPendingTask.setIsHandle(0L); // ✅ 未处理
                            nextPendingTask.setStepNo(accraditationRecord.getStepNo() + 1); // ✅ 步骤3
                            nextPendingTask.setCreateTime(new Date());
                            
                            pendingTasksService.insertPendingTasks(nextPendingTask);
                            System.out.println("✅ 已创建步骤3待办任务: " + nextStepName);
                            System.out.println("   步骤号: " + nextPendingTask.getStepNo());
                            System.out.println("   状态: is_handle=" + nextPendingTask.getIsHandle());
                            System.out.println("   任务ID: " + nextPendingTask.getTaskId());
                            
                            // 更新审批记录中的下一步信息
                            accraditationRecord.setNextStep(nextStepName);
                            accraditationRecord.setNextApprover(nextTask.getAssignee());
                            accraditationRecord.setNextApproverRole(nextApproverRole);
                        } else {
                            System.out.println("未查询到下一个任务，流程可能已结束");
                        }
                    } else {
                        // 审批拒绝，结束流程
                        System.out.println(">>> 处理审批拒绝逻辑 <<<");
                        System.out.println("=== 退住申请审批拒绝，流程结束 ===");
                        System.out.println("业务ID: " + busId);
                        System.out.println("拒绝步骤: " + accraditationRecord.getStepNo());
                        System.out.println("拒绝意见: " + accraditationRecord.getOpinion());
                        
                        // 1. 完成当前工作流任务（以拒绝方式完成）
                        if (accraditationRecord.getExtraField1() != null && !accraditationRecord.getExtraField1().trim().isEmpty()) {
                            try {
                                String workflowTaskId = accraditationRecord.getExtraField1();
                                System.out.println("尝试完成工作流任务: " + workflowTaskId);
                                
                                // 首先检查任务是否存在
                                org.activiti.engine.task.Task task = taskService.createTaskQuery()
                                    .taskId(workflowTaskId)
                                    .singleResult();
                                
                                if (task != null) {
                                    System.out.println("✅ 找到工作流任务: " + task.getName() + " (ID: " + workflowTaskId + ")");
                                    taskService.complete(workflowTaskId);
                                    System.out.println("✅ 完成工作流任务（拒绝）: " + workflowTaskId);
                                } else {
                                    System.out.println("⚠️ 工作流任务不存在或已被完成: " + workflowTaskId);
                                    System.out.println("继续执行拒绝处理逻辑...");
                                }
                            } catch (Exception e) {
                                System.err.println("❌ 完成工作流任务失败: " + e.getMessage());
                                System.err.println("继续执行拒绝处理逻辑...");
                                e.printStackTrace();
                            }
                        } else {
                            System.out.println("⚠️ 工作流任务ID为空，跳过工作流任务完成");
                        }
                        
                        // 2. 更新当前待办任务状态为已处理（拒绝状态）
                        if (accraditationRecord.getHandleType() != null) {
                            try {
                                System.out.println("=== 开始更新拒绝步骤的待办任务状态 ===");
                                System.out.println("待办任务ID: " + accraditationRecord.getHandleType());
                                
                                PendingTasks currentTask = pendingTasksService.selectPendingTasksById(accraditationRecord.getHandleType());
                                if (currentTask != null) {
                                    System.out.println("找到待办任务: " + currentTask.getId() + 
                                        ", 步骤: " + currentTask.getStepNo() + 
                                        ", 当前状态: " + currentTask.getIsHandle());
                                    
                                    // 更新状态
                                    currentTask.setIsHandle(1L); // 设置为已处理（拒绝）
                                    currentTask.setFinishTime(new Date());
                                    currentTask.setStatus(3L); // 3=已拒绝
                                    
                                    int updateResult = pendingTasksService.updatePendingTasks(currentTask);
                                    System.out.println("更新结果: " + (updateResult > 0 ? "成功" : "失败"));
                                    
                                    // 验证更新结果
                                    PendingTasks updatedTask = pendingTasksService.selectPendingTasksById(accraditationRecord.getHandleType());
                                    if (updatedTask != null) {
                                        System.out.println("✅ 验证更新结果: " + updatedTask.getId() + 
                                            ", 步骤: " + updatedTask.getStepNo() + 
                                            ", 新状态: " + updatedTask.getIsHandle() + 
                                            ", 完成时间: " + updatedTask.getFinishTime());
                                    }
                                } else {
                                    System.out.println("❌ 未找到待办任务ID: " + accraditationRecord.getHandleType());
                                }
                            } catch (Exception e) {
                                System.err.println("❌ 更新拒绝步骤待办任务状态失败: " + e.getMessage());
                                e.printStackTrace();
                            }
                        } else {
                            System.out.println("❌ 待办任务ID为空，无法更新状态");
                        }
                        
                        // 3. 关键：不生成下一步待办任务（拒绝时流程结束）
                        System.out.println("✅ 拒绝处理完成，不生成下一步待办任务");
                        
                        // 4. 强制清理：删除所有后续步骤的待办任务（拒绝时流程结束）
                        try {
                            System.out.println("=== 开始清理所有后续步骤的待办任务 ===");
                            
                            // 查询该业务ID下的所有待办任务
                            com.lekang.system.domain.PendingTasks queryTask = new com.lekang.system.domain.PendingTasks();
                            queryTask.setBussniessId(busId);
                            queryTask.setType(accraditationRecord.getType()); // ⚠️ 关键修复：使用记录的type
                            java.util.List<com.lekang.system.domain.PendingTasks> allTasks = pendingTasksService.selectPendingTasksList(queryTask);
                            
                            if (allTasks != null && !allTasks.isEmpty()) {
                                System.out.println("业务ID " + busId + " 的所有待办任务:");
                                for (com.lekang.system.domain.PendingTasks task : allTasks) {
                                    System.out.println("  - 任务ID: " + task.getId() + 
                                        ", 步骤: " + task.getStepNo() + 
                                        ", 状态: " + task.getIsHandle() + 
                                        ", 标题: " + task.getTitle());
                                }
                                
                                // 删除所有步骤号大于当前拒绝步骤的任务
                                Long rejectedStep = accraditationRecord.getStepNo();
                                int deletedCount = 0;
                                
                                for (com.lekang.system.domain.PendingTasks task : allTasks) {
                                    if (task.getStepNo() != null && task.getStepNo() > rejectedStep) {
                                        pendingTasksService.deletePendingTasksById(task.getId());
                                        System.out.println("✅ 已删除后续步骤待办任务: " + task.getId() + " (步骤" + task.getStepNo() + ")");
                                        deletedCount++;
                                    }
                                }
                                
                                if (deletedCount > 0) {
                                    System.out.println("✅ 共删除了 " + deletedCount + " 个后续步骤的待办任务");
                                } else {
                                    System.out.println("✅ 没有发现需要删除的后续步骤待办任务");
                                }
                            } else {
                                System.out.println("未找到业务ID " + busId + " 的待办任务");
                            }
                        } catch (Exception e) {
                            System.err.println("❌ 清理后续步骤待办任务时发生异常: " + e.getMessage());
                            e.printStackTrace();
                        }
                        
                        // 5. 可以在这里添加其他拒绝后的处理逻辑
                        // 比如发送通知、记录拒绝原因等
                    }
                }
            } else if (businessType == 2L) {
                // 请假申请
                LeaveRequest leaveRequest = requestService.selectLeaveRequestById(busId);
                if (leaveRequest != null) {
                    if(accraditationRecord.getAuditStatus()==1){
                        leaveRequest.setLeaveStatus("请假中");
                    }else{
                        leaveRequest.setLeaveStatus("拒绝");
                    }
                    requestService.updateLeaveRequest(leaveRequest);
                }
            } else if (businessType == 3L) {
                // 入住申请 - 不需要在这里处理，由CheckInManagementServiceImpl处理
                // 这里可以添加其他业务类型的处理逻辑
            }
        }
        return i;

    }
    
    /**
     * 根据任务名称和当前步骤获取下一步名称
     */
    private String getNextStepName(String taskName, Long currentStep) {
        if (taskName.contains("申请单初步审批")) {
            return "退住审批员上传解除协议";
        } else if (taskName.contains("上传解除协议")) {
            return "退住审批员调整账单";
        } else if (taskName.contains("调整账单")) {
            return "退住审批员完成账单审批";
        } else if (taskName.contains("完成账单审批")) {
            return "退住审批员退住审批";
        } else if (taskName.contains("退住审批")) {
            return "退住审批员完成最终费用清算";
        } else if (taskName.contains("完成最终费用清算")) {
            return "流程结束";
        }
        return "下一步操作";
    }
    
    /**
     * 根据任务名称获取审批人角色
     */
    private String getNextApproverRole(String taskName) {
        if (taskName.contains("申请单初步审批") || 
            taskName.contains("上传解除协议") || 
            taskName.contains("调整账单") || 
            taskName.contains("完成账单审批") || 
            taskName.contains("完成最终费用清算")) {
            return "退住审批员";
        } else if (taskName.contains("退住审批")) {
            return "退住审批员";
        }
        return "审批员";
    }

    /**
     * 修改审批记录
     * 
     * @param accraditationRecord 审批记录
     * @return 结果
     */
    @Override
    public int updateAccraditationRecord(AccraditationRecord accraditationRecord)
    {
        accraditationRecord.setUpdateTime(DateUtils.getNowDate());
        return accraditationRecordMapper.updateAccraditationRecord(accraditationRecord);
    }

    /**
     * 批量删除审批记录
     * 
     * @param ids 需要删除的审批记录主键
     * @return 结果
     */
    @Override
    public int deleteAccraditationRecordByIds(Long[] ids)
    {
        return accraditationRecordMapper.deleteAccraditationRecordByIds(ids);
    }

    /**
     * 删除审批记录信息
     * 
     * @param id 审批记录主键
     * @return 结果
     */
    @Override
    public int deleteAccraditationRecordById(Long id)
    {
        return accraditationRecordMapper.deleteAccraditationRecordById(id);
    }
}
